/* eslint-disable array-callback-return */
/* eslint-disable consistent-return */
/* eslint-disable no-async-promise-executor */
import Taro from '@tarojs/taro';
import { getPlatform } from '@UTILS/common'
import api from '@API'

const global = {}
export const getWxTemplate = () => new Promise(async resolve => {
  if (global.templateData) {
    return resolve(global.templateData)
  }
  const { isWX } = getPlatform();
  if (!isWX) return resolve()
  const data = await api.getWxServiceNoticeTemplate()
  resolve(data)
})
const getTemplateIdsFromEvents = events => {
  const data = global.templateData
  const templateIds = []
  data && events.forEach(item => {
    data[item] && templateIds.push(data[item].TemplateId)
  })
  return templateIds
}
const covertWeChatNoticeStates = (subscribeResult, events, extraData = {}) => {
  if (!subscribeResult || !global.templateData) return
  const NoticeStateArray = []
  events.map(item => {
    if (!global.templateData[item]) return
    const templateId = global.templateData[item].TemplateId
    NoticeStateArray.push({
      TemplateId: templateId,
      State: subscribeResult[templateId] === 'accept' ? 'Accept' : 'Reject',
      NotificationType: item,
      ...extraData
    })
  })
  return NoticeStateArray
}

export const requestSubscribeAndSave = async (events, extraData) => {
  try {
    const { isWX } = getPlatform();
    if (!isWX) return
    const wxtemplate = await getWxTemplate()
    global.templateData = wxtemplate
    const templateIds = getTemplateIdsFromEvents(events)
    const result = await requestSubscribeMessage(templateIds)
    const noticeStateArray = covertWeChatNoticeStates(result, events, extraData)
    await api.saveWeChatNoticeStates({ NoticeStateArray: noticeStateArray })
  } catch (err) {
    console.error('err:', err)
  }
}

export const requestSubscribeAndSaveWithResult = async (events, extraData) => {
  try {
    const { isWX } = getPlatform();
    if (!isWX) return
    const wxtemplate = await getWxTemplate()
    global.templateData = wxtemplate
    const templateIds = getTemplateIdsFromEvents(events)
    const result = await requestSubscribeMessage(templateIds)
    if (JSON.stringify(result).includes('reject')) {
      return { errMsg: true }
    }
    const noticeStateArray = covertWeChatNoticeStates(result, events, extraData)
    await api.saveWeChatNoticeStates({ NoticeStateArray: noticeStateArray })
  } catch (err) {
    console.error('err:', err)
  }
}

export const requestSubscribeMessage = templateIds => {
  const { isWX } = getPlatform();
  if (!isWX || !templateIds) return
  if (Array.isArray(templateIds) && templateIds.length === 0) return
  return new Promise(resolve => {
    Taro.requestSubscribeMessage({
      tmplIds: templateIds,
      success: result => {
        resolve(result)
      },
      fail: fail => {
        resolve(fail)
      }
    })
  })
}
